package com.cll.learn.deadlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/5/15 20:54
 */
public class MyLockThread implements Runnable{

    private static ReentrantLock lock1 = new ReentrantLock();
    private static ReentrantLock lock2 = new ReentrantLock();

    int lockState;

    public MyLockThread(int lockState) {
        this.lockState = lockState;
    }

    @Override
    public void run() {
        try {
            if (1 == lockState) {
                lock1.lock();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                lock2.lock();
            } else {
                lock2.lock();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                lock1.lock();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock1.isHeldByCurrentThread()) {
                lock1.unlock();
            }
            if (lock2.isHeldByCurrentThread()) {
                lock2.unlock();
            }
        }
    }
}
